package cn.lls.controller.employee;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.base.util.MD5Util;
import cn.lls.base.util.TokenUtil;
import cn.lls.dto.EmployeeLoginDTO;
import cn.lls.req.emp.EMPAccountReq;
import cn.lls.service.IEmployeeService;
import cn.lls.service.IPermissionService;
import cn.lls.vo.common.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 员工登录控制器
 *
 * @ClassName EmployeeLoginController
 * @Author 划水艺术家
 * @Date 2022/11/22 14:05
 * @Version 1.0
 **/

@Slf4j
@RequestMapping("/emp/login")
@RestController
@Api(tags = "员工登录控制器")
public class EmployeeLoginController {


    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @PostMapping
    @ApiOperation(value = "员工登录", notes = "员工登录", response = R.class, httpMethod = "POST")
    public R empLogin(@RequestBody @Validated EMPAccountReq empAccountReq,
                     BindingResult bindingResult){

        EmployeeLoginDTO one = employeeService.empLogin(empAccountReq);
        log.info("one = {}", one);
        // 账户不存在
        if (one == null){
            throw new LlsException(ResultCode.ACCOUNT_NOT_EXISTS);
        }
        // 密码错误
        if (!MD5Util.MD5Encode(empAccountReq.getLoginPassword()).equals(one.getLoginPassword())){
            return R.fail(ResultCode.PWD_FALSE, "密码错误");
        }
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(TokenUtil.createToken(one.getUserId(),
                LlsEnum.LlsIdentify.EMPLOYEE));
        loginVO.setIdentify(LlsEnum.LlsIdentify.EMPLOYEE);
        loginVO.setUserId(one.getUserId());
        loginVO.setCompanyId(one.getCompanyId());
        loginVO.setMenuList(permissionService.getMenusByRoleId(one.getRoleId()));
        loginVO.setName(one.getName());
        loginVO.setOrganName(one.getOrganName());
        return R.success(loginVO);
    }
}
